import React, { Component } from 'react';
import TheTable from "@/components/TheTable";
import ThePagination from "../../../components/ThePagination";
import TheButton from "@/components/TheButton";
import TheQueryForm from '@/components/TheQueryForm';
import TheDialog from '@/components/TheDialog';
import moment from 'moment';
import { apiAppCouponInfoPage, apiAppCouponInfoEnd } from '@/request/couponManagement'
// import SendCoupons from './components/sendCoupons'
import { Space, Tabs, message } from "antd";
import store from "@/store/store"
// import './style.scss'
const { TabPane } = Tabs;

class Index extends Component {
  constructor() {
    super();
    this.queryFormRef_1 = React.createRef()
    this.state = {
      sendDialog: false,
      indcutsValue: {},
      sendCouponId: '',
      defaultActiveKey: '1',
      form_show_1: true,
      searchOption_1: [
        {
          field: 'couponTitle',
          label: '优惠券名称',
          placeholder: '请输入',
          required: false,
          rules: [],
          type: 'Input',
        },
      ],
      columns_1: [
        {
          title: "优惠券ID",
          dataIndex: "couponId",
          key: "couponId",
        },
        {
          title: "优惠券名称",
          dataIndex: "couponTitle",
          key: "couponTitle",
          ellipsis: {
            showTitle: false,
          },
          onCell: () => {
            return {
              style: {
                maxWidth: 200,
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
              }
            }
          },
        },
        {
          title: "优惠券类型",
          dataIndex: "couponType",
          key: "couponType",
          render: (text, render) => {
            let label = ''
            switch (text) {
              case "J":
                label = "代金券"
                break;
              case "Z":
                label = "折扣券"
                break;
              default:
                label = "字段值错误"
            }
            return label
          }
        },
        {
          title: "范围",
          dataIndex: "commodityScope",
          key: "commodityScope",
          render: (text, render) => {
            let label = ''
            switch (text) {
              case 0:
                label = "全部商品可用"
                break;
              case 1:
                label = "限制品类可用"
                break;
              case 2:
                label = "商品券"
                break;
              default:
                label = "字段值错误"
            }
            return label
          }
        },
        {
          title: "优惠",
          dataIndex: "couponPrice",
          key: "couponPrice",
          render: (text, render) => {
            let label = ''
            switch (render.usePrice) {
              case -1:
                label = '无门槛，'
                break;
              default:
                label = "满" + (render.usePrice) / 100 + "可用，"
            }
            switch (render.couponType) {
              case 'J':
                label += "减免" + text / 100 + "元"
                break;
              case 'Z':
                label += "打" + text / 10 + "折"
                if (render.couponMaxPrice !== -1) {
                  label += '，最大折扣金额' + (render.couponMaxPrice) / 100 + '元'
                }
                break;
              default:
                label = "字段值错误"
            }
            return label
          }
        },
        {
          title: "状态",
          dataIndex: "activeStatus",
          key: "activeStatus",
          render: (text, render) => {
            let label = ''
            switch (text) {
              case 0:
                label = "未开始"
                break;
              case 1:
                label = "进行中"
                break;
              case 2:
                label = "已结束"
                break;
              default:
                label = "字段值错误"
            }
            return label
          }
        },
        {
          title: "最近修改时间",
          dataIndex: "updateTime",
          key: "updateTime",
          render: (text, render) => {
            return text ?? '/'
          }
        },
      ],
      dataSource_1: [],
      pageData_1: {
        pageNo: 1,
        pageSize: 10
      },
      total_1: 0,
      queryForm_1: {},
      dataSource_2: [],
      pageData_2: {
        pageNo: 1,
        pageSize: 10
      },
      total_2: 0,
      queryForm_2: {},
      selectedKeys: {
        1: {},
        2: {}
      },
      selectedRowKeysAll: {
        1: {},
        2: {}
      }
    }
  }
  componentDidMount() {
    let searchParams = store.getState().searchValue
    console.log(searchParams);
    if (searchParams) {
      let { pageNo, pageSize, queryForm, pathName } = searchParams
      let { defaultActiveKey } = this.state;
      if (searchParams && pageNo && pathName === 'couponsListSearch') {
        this.setState({
          ["queryForm_" + defaultActiveKey]: queryForm,
          ["pageData_" + defaultActiveKey]: {
            pageNo,
            pageSize
          }
        }, () => {
          this["queryFormRef_" + defaultActiveKey].onSetDefault({
            ...queryForm
          })
          this.getData()
        })
      } else {
        this.getData()
      }
    } else {
      this.getData()
    }
  }
  // 查看
  onView(id) {
    this.props.history.push(`/couponManagement/couponsList/add/view/${id}`);
  }
  // 编辑
  onEdit(id) {
    this.props.history.push(`/couponManagement/couponsList/add/edit/${id}`);
  }
  overNow(id, timeType) {
    React.$confirm({
      title: "提示",
      content: `提前结束优惠券活动可能导致正在领取的消费者领取失败，是否继续关闭？`,
      onOk: async () => {
        let res = await apiAppCouponInfoEnd({
          couponId: id,
          timeType
        })
        if (res.code === 0 && res.data) {
          React.$message({
            type: 'info',
            content: '结束成功'
          })
          await this.getData()
        }
      },
    });
  }
  CDKList(id) {
    this.props.history.push(`/coupons/CDKlist/${id}`)
  }
  getRecord(id) {
    this.props.history.push(`/coupons/Receipt/${id}`)
  }
  sendCoupons(couponId, value) {
    this.setState({
      sendCouponId: couponId,
      indcutsValue: value,
      sendDialog: true
    })
  }
  sendhandleCancel = () => {
    this.setState({
      couponId: "",
      couponName: "",
      sendDialog: false
    });
  }
  getData = async (values) => {
    let { defaultActiveKey } = this.state;
    let { pageNo, pageSize } = this.state["pageData_" + defaultActiveKey]
    let couponSpecies = ""
    if (values && 'time' in values && values.time) {
      values.startTime = moment(values.time[0]).format('YYYY-MM-DD') + " 00:00:00"
      values.stopTime = moment(values.time[1]).format('YYYY-MM-DD') + " 23:59:59"
      delete values.time
    }
    if (defaultActiveKey === "1") {
      couponSpecies = "P"
    } else {
      couponSpecies = "M"
    }
    if (values && 'type' in values) {
      if (values.type === 'Q') {
        delete values.type
      }
    }
    this.setState({
      ["queryForm_" + defaultActiveKey]: values === undefined ? this.state["queryForm_" + defaultActiveKey] : { ...values }
    }, async () => {
      let params = {
        pageNo,
        pageSize,
        couponSpecies,
        couponSourceCard: 1,
        activeStatus: 1,
        over: 0,
        queryForm: {
          ...values
        }
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'couponsListSearch',
          ...params
        }
      })
      let postParams = {
        ...this.state["queryForm_" + defaultActiveKey],
        couponSpecies,
        couponSourceCard: 1,
        activeStatus: 1,
        over: 0,
        pageNo,
        pageSize,
      }

      let res = await apiAppCouponInfoPage(postParams)
      if (res.rows) {
        this.setState({
          ["dataSource_" + defaultActiveKey]: res.rows,
          ["total_" + defaultActiveKey]: res.totalCount,
          ["pageData_" + defaultActiveKey]: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          }
        })
      }
    })
  }
  // 添加优惠券
  goAdd = (e) => {
    this.props.history.push(`/couponManagement/couponsList/add/create/null`);
  }
  // 切换tab
  onTabChange = (e) => {
    this.setState({
      defaultActiveKey: e
    }, () => {
      this.getData()
    })
  }
  pageChange = (pageNo, pageSize) => {
    let { defaultActiveKey } = this.state
    this.setState({
      ["pageData_" + defaultActiveKey]: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  };

  onReset() {
    let { defaultActiveKey } = this.state
    this.setState({
      ["queryForm_" + defaultActiveKey]: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }

  onChange = (selectedRowKeys, selectedRows) => {
    console.log(selectedRowKeys, "selectedRowKeys");
    const { defaultActiveKey, } = this.state
    let pageNo = this.state["pageData_" + defaultActiveKey].pageNo
    let selectedKeys = { ...this.state.selectedKeys }
    let selectedRowKeysAll = { ...this.state.selectedRowKeysAll }
    selectedKeys[defaultActiveKey][pageNo] = selectedRows
    selectedRowKeysAll[defaultActiveKey][pageNo] = selectedRowKeys
    console.log(selectedKeys);
    this.setState({
      selectedKeys,
      selectedRowKeysAll
    })
  }

  onFormSearch(values) {
    let { defaultActiveKey } = this.state
    this.setState({
      ["pageData_" + defaultActiveKey]: { pageNo: 1, pageSize: 10 }
    }, () => {
      this.getData(values)
    })
  }
  // 下载导入模板
  download = (url) => {
    const a = document.createElement('a')
    a.href = 'https://hqmimage.oss-cn-beijing.aliyuncs.com/%E7%94%B5%E8%AF%9D%E5%8F%B7%E6%A8%A1%E6%9D%BF.xlsx'
    document.body.append(a)
    a.click()
    a.remove()
  }
  render() {
    let {
      defaultActiveKey,
      form_show_1,
      searchOption_1,
      columns_1,
      dataSource_1,
      pageData_1,
      total_1,
      dataSource_2,
      pageData_2,
      total_2,
      sendCouponId,
      indcutsValue,
      sendDialog,
      selectedKeys,
      selectedRowKeysAll
    } = this.state
    let selectedRowKeys = []
    if (defaultActiveKey === 1) {
      selectedRowKeys = selectedRowKeysAll[defaultActiveKey][pageData_1.pageNo]
    } else {
      selectedRowKeys = selectedRowKeysAll[defaultActiveKey][pageData_2.pageNo]
    }
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onChange,
    }
    return (
      <div className="p-layout-box">
        {/* <div style={{ marginBottom: 10 }}>
          <TheButton haspermi={["couponManagement:list:add"]} type="primary" size="middle" onClick={this.goAdd}>
            新建优惠券
          </TheButton>
        </div> */}
        <Tabs
          activeKey={defaultActiveKey}
          type="card"
          // size={'small'}
          onChange={(e) => this.onTabChange(e)}
          tabBarExtraContent={
            <>
              {/*<TheButton type="default" size="middle" onClick={() => { this.download("") }}>*/}
              {/*    下载导入模板*/}
              {/*</TheButton>*/}
            </>
          }
        >
          <TabPane tab="线上商城" key="1" forceRender>
            <TheQueryForm ref={(ref) => this.queryFormRef_1 = ref} show={form_show_1}
              option={searchOption_1}
              onGetValues={(values) => this.onFormSearch(values)}
              onReset={(values) => this.onReset(values)}
            >
            </TheQueryForm>
            <TheTable
              scroll={{ x: "max-content", y: '63vh' }}
              columns={columns_1}
              dataSource={dataSource_1}
              // loading={true}
              rowKey={record => record.couponId}
              rowSelection={rowSelection}
            />
            <ThePagination
              pageNo={pageData_1.pageNo}
              pageSize={pageData_1.pageSize}
              total={total_1}
              pageChange={this.pageChange}
            />
          </TabPane>
          <TabPane tab="门店服务" key="2" forceRender >
            <TheQueryForm ref={(ref) => this.queryFormRef_1 = ref} show={form_show_1}
              option={searchOption_1}
              onGetValues={(values) => this.onFormSearch(values)}
              onReset={(values) => this.onReset(values)}
            >
            </TheQueryForm>
            <TheTable
              scroll={{ x: "max-content", y: '63vh' }}
              columns={columns_1}
              dataSource={dataSource_2}
              // loading={true}
              rowKey={record => record.couponId}
              rowSelection={rowSelection}
            />
            <ThePagination
              pageNo={pageData_2.pageNo}
              pageSize={pageData_2.pageSize}
              total={total_2}
              pageChange={this.pageChange}
            />
          </TabPane>
        </Tabs>
        <TheDialog
          title={'指定用户发放优惠券'}
          visible={sendDialog}
          footer={null}
          handleCancel={this.sendhandleCancel}
          width={440}
        >
          {/* <SendCoupons
            couponId={sendCouponId}
            indcutsValue={indcutsValue}
            type={"indcuts"}
            handleCancel={this.sendhandleCancel} /> */}
        </TheDialog>
      </div>
    );
  }
}
export default Index;
